<?php

namespace common\models;

use common\helpers\commonApi;
use common\helpers\RedisApi;
use common\helpers\TransformApi;
use Yii;
use yii\db\Exception;

/**
 * This is the model class for table "{{%order_retreat}}".
 *
 * @property int $id
 * @property string|null $order_sn 订单号
 * @property int|null $userid 用户id
 * @property float|null $amount 金额
 * @property string|null $content 申请原因
 * @property string|null $imgs 图片
 * @property int|null $review_status 审核状态
 * @property string|null $review_time 审核时间
 * @property string|null $review_remarks 审核备注
 * @property string|null $create_time 申请时间
 * @property string|null $update_time 修改时间
 * @property int|null $campus_id 校区
 * @property int|null $order_id 订单号id
 * @property float|null $already_amount 已退款金额
 * @property string|null $refund_sn 退款订单号
 * @property string|null $callback_info 回调信息
 */
class OrderRetreat extends BaseModel
{
    /**
     * {@inheritdoc}
     */
    public static function tableName()
    {
        return '{{%order_retreat}}';
    }

    /**
     * {@inheritdoc}
     */
    public function rules()
    {
        return [
            [['userid', 'review_status','campus_id','order_id'], 'integer'],
            [['amount','already_amount'], 'number'],
            [['content','callback_info'], 'string'],
            [['review_time', 'create_time', 'update_time'], 'safe'],
            [['order_sn', 'imgs', 'review_remarks','refund_sn'], 'string', 'max' => 255],
        ];
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'order_sn' => '订单号',
            'userid' => '用户id',
            'amount' => '金额',
            'content' => '申请原因',
            'imgs' => '图片',
            'review_status' => '审核状态',
            'review_time' => '审核时间',
            'review_remarks' => '审核备注',
            'create_time' => '申请时间',
            'update_time' => '修改时间',
            'campus_id' => '校区',
            'order_id' => '订单号id',
            'already_amount' => '已退款金额',
            'refund_sn' => '退款订单号',
            'callback_info' => '回调信息',
        ];
    }

    /**
     * 退款订单号
     * @return mixed|string
     */
    public static function makeOrderid()
    {
        $orderId = time() . '' . rand(1000, 9999);
        if (self::find()->where(['refund_sn' => $orderId])->exists()) {
            $orderId = self::makeOrderid();
        }
        return $orderId;
    }
    /**
     * 申请退货
     * @param $orderSn 订单号
     * @param $userid 用户id
     * @return array
     */
    public function retreat($orderSn, $userid)
    {
        $order = Order::find()->where(['order_sn' => $orderSn, 'userid' => $userid])->one();
        if (!$order) {
            return commonApi::message('暂无订单', false);
        }
        $statuIsretreat = Yii::$app->params['can_retreat'];
        if (!in_array($order->order_status, $statuIsretreat)) {
            return commonApi::message('该订单不支持退货', false);
        }
        if ($order->refund_status !== 0) {
            return commonApi::message('该订单不支持退货', false);
        }
        $key = 'retreat_' . $orderSn;
        $redis = new RedisApi($key);
        $result = $redis->verificLock();
        if ($result) {
            return commonApi::message('请勿重复操作！', false);
        }
        $redis->lock($orderSn);
        $redis->expire(120);
        $model = new OrderRetreat();
        $model->userid = $userid;
        $model->order_sn = $orderSn;
        $model->amount = $order->pay_amount;
        $model->campus_id = $order->campus_id;
        $model->order_id = $order->id;
        $model->review_status = 0;
        $order->refund_status = 1;
        TransformApi::tx(function () use ($order, $model) {
            if ($order->save() && $model->save()) {
                OrderLog::add(0, $order->order_sn, $order->userid, '', '用户申请退货', '用户申请退货');
                return commonApi::message('申请中，等待审核');
            }
            throw new Exception(commonApi::getModelError($order));
        }, $result);
        $redis->unlock();
        return $result;
    }
}
